<%@ page import="java.awt.image.BufferedImage" %>
<%@ page import="java.awt.*" %>
<%@ page import="java.util.Random" %>
<%@ page import="javax.imageio.ImageIO" %>

<%--生成随机验证码--%>
<%@ page contentType="image/JPEG;charset=UTF-8" pageEncoding="UTF-8" language="java" %>
<%!
    //获取随机颜色
    Color getRandColor(int fc,int bc) {
        Random random = new Random();
        if (fc > 255) fc = 255;
        if (bc > 255) bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
%>
<%
    response.setCharacterEncoding("utf-8");
    // 设置响应头以禁止缓存
    response.setHeader("Cache-Control", "no-cache");// HTTP 1.1
    //创建图像
    int width = 60, height = 20;
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    //获取画笔
    Graphics g = image.getGraphics();
    //设定背景色
    g.setColor(getRandColor(200, 250));
    g.fillRect(0, 0, width, height);
    //随机产生四位数字
    Random rnd = new Random();
    int randNum = rnd.nextInt(9000) + 1000; //生成1000-9999的随机数
    String randStr = String.valueOf(randNum);
    //将验证码存入session
    session.setAttribute("randStr", randStr);
    //设定字体
    g.setFont(new Font("Times New Roman", Font.PLAIN, 20));
    //显示到图像中
    g.setColor(Color.BLACK);
    g.drawString(randStr, 10, 17);
    //随机产生100个干扰点
    for (int i = 0; i < 100; i++) {
        int x = rnd.nextInt(width);
        int y = rnd.nextInt(height);
        g.drawOval(x, y, 1, 1);
    }
    // 图象生效
    g.dispose();
    //输出到页面
    ImageIO.write(image, "jpg", response.getOutputStream());
    out.clear();
    out = pageContext.pushBody();
%>
